import { FC, ReactNode, useState, useEffect, useMemo, useContext } from "react";
import styles from "./index.module.less";
import useAnomaly from "../../components/MainBody/hooks/useAnomaly";
import Tab from "../Tab";
import { BigScreenContext } from "../../context/BigScreenContext";
import classNames from "classnames";
import MarkerInfo from "../MarkerInfo";
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import BarMarker, { BarItem } from "../BarMarker";
import useCharts from "./useCharts";
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { getAnomalyType } from "../../constants";
import useMarker from "./useMarker";
import ChartPointModal from "../ChartPointModal";
import dynamicBackground1 from "@/assets/images/flow-bottom.webm"
import dynamicBackground2 from "@/assets/images/flow-top.webm"

// 定义标记点位置接口
export interface MarkerPosition {
  x: number; // x坐标的百分比值
  y: number; // y坐标的百分比值
}

// 定义标记项接口
export interface MarkerItem {
  id: string;
  title: string;
  name?: string;
  visible?: boolean;
  value: string;
  description?: string;
  type: "red" | "yellow" | "green" | "gray";
  position: MarkerPosition;
  updateTime?: string;
  evaluationItemId?: string; // 添加评估项ID，用于获取趋势数据
  predictTime?: string; // 添加预测时间点
}

interface BGContainerProps {
  children: ReactNode;
}

const BGContainer: FC<BGContainerProps> = ({ children }) => {
  // 使用异常钩子获取异常数据和处理函数
  const { selectedAnomaly, setSelectedAnomaly } = useAnomaly();
  const { currentKey, activeTab, setActiveTab } = useContext(BigScreenContext);
  // 状态用于跟踪视口尺寸
  const [viewportSize, setViewportSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });

  // 添加图表点击弹窗相关状态
  const [modalVisible, setModalVisible] = useState(false);
  const [clickedPointData, setClickedPointData] = useState<{
    name: string;
    value: any;
    dataIndex: number;
    seriesIndex: number;
  } | undefined>(undefined);
  const [clickedMarkerTitle, setClickedMarkerTitle] = useState<string>('');
  const [clickedMarkerType, setClickedMarkerType] = useState<"red" | "yellow" | "green" | "gray">('green');
  // 添加评估项名称和标签名称状态
  const [clickedEvaluationItemName, setClickedEvaluationItemName] = useState<string>('');
  const [clickedTagName, setClickedTagName] = useState<string>('');
  // 添加状态存储MarkerInfo的图表数据
  const [markerTrendData, setMarkerTrendData] = useState<any>(null);

  // 使用charts钩子，实现轮询
  const { currentDevice, currentPathDevice, trendData } = useCharts(currentKey ?? "", activeTab);
  // 使用marker钩子，处理标记点和柱子相关逻辑
  const { currentMarker, getMarkerPixelPosition, getConfirmedMarkerPixelPosition, getBars } = useMarker({
    trendData,
    currentKey,
    currentDevice,
    currentPathDevice,
    viewportSize,
  });
  // Tab选项列表
  // const tabOptions = ["整体装置", "裂解炉", "压缩机"];
  const tabOptions = ["裂解炉", "压缩机"];

  const selectedMarker = useMemo(() => {
    console.log('selectedAnomaly', selectedAnomaly);
    return selectedAnomaly ? {
      visible: true,
      id: selectedAnomaly.id,
      title: selectedAnomaly.name,
      name: selectedAnomaly.evaluationItemName,
      value: selectedAnomaly.location,
      description: selectedAnomaly.description,
      type: selectedAnomaly.type,
      position: selectedAnomaly.position || { x: 50, y: 50 }, // 默认位置在中心
      updateTime: selectedAnomaly.updateTime,
      evaluationItemId: selectedAnomaly.evaluationItemId, // 添加评估项ID
      predictTime: selectedAnomaly.predictTime, // 添加预测时间点
      abnormalCause: selectedAnomaly.description, // 添加异常原因
    } : null;
  }, [selectedAnomaly, activeTab]);

  // 使用useMemo创建confirmedMarker，只有当trendData或currentDevice变化时才会重新计算
  const confirmedMarker: any = useMemo(() => {
    if (trendData?.length > 0 && currentDevice !== "all") {
      return {
        visible: true,
        id: trendData[0].evaluationItemName || 'marker-id',
        title: trendData[0].evaluationItemName || '参数点',
        type: "green" as const,
        predictTime: trendData[0].predictTime, // 添加预测时间点
      };
    }
    return {
      visible: false,
      id: "",
      title: currentDevice,
      type: "green",
    };
  }, [trendData, currentDevice]);

  // 添加视频加载状态
  const [videoLoaded, setVideoLoaded] = useState(false);

  // 添加MarkerInfo透明度状态
  const [isMarkerTransparent, setIsMarkerTransparent] = useState(false);

  // 监听视口尺寸变化
  useEffect(() => {
    const handleResize = () => {
      setViewportSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    };

    window.addEventListener("resize", handleResize);
    return () => {
      window.removeEventListener("resize", handleResize);
    };
  }, []);

  // 根据selectedMarker计算像素位置
  const markerPixelPosition = useMemo(() => {
    if (!selectedMarker) return null;
    return getMarkerPixelPosition(selectedMarker.position);
  }, [selectedMarker, getMarkerPixelPosition]);

  // 处理Tab切换
  const handleTabChange = (tab: string) => {
    setActiveTab(tab);
  };

  // 获取背景图className
  const getBackgroundClassName = () => {
    return classNames(styles["threeD-container"], {
      [styles["bg-136"]]:
        activeTab === "压缩机" || ["param", "path"].includes(currentKey ?? ""),
      [styles["bg-137"]]:
        activeTab !== "压缩机" || ["param", "path"].includes(currentKey ?? ""),
    });
  };

  const getDynamicBackground = () => {
    if (activeTab === "压缩机" || ["param", "path"].includes(currentKey ?? "")) {
      return dynamicBackground1
    }
    if (activeTab !== "压缩机" || ["param", "path"].includes(currentKey ?? "")) {
      return dynamicBackground2
    }
    // 返回默认视频，确保总是有返回值
    return dynamicBackground2;
  };

  // 处理视频加载完成事件
  const handleVideoLoaded = () => {
    setVideoLoaded(true);
  };

  // 处理图表点击事件
  const handleChartPointClick = (params: { name: string; value: any; dataIndex: number; seriesIndex: number; }, markerTitle: string, markerType: "red" | "yellow" | "green" | "gray", markerChartData?: any) => {
    setClickedPointData(params);
    setClickedMarkerTitle(markerTitle);
    setClickedMarkerType(markerType);
    setMarkerTrendData(markerChartData);
    // 设置评估项名称和标签名称
    // 在多线图模式下，从trendData中获取对应的标签名称
    if (trendData.length > 0) {
      if (params.seriesIndex !== undefined && trendData.length > params.seriesIndex) {
        const seriesData = trendData[params.seriesIndex];
        if (seriesData) {
          console.log('seriesData', seriesData);
          setClickedEvaluationItemName(seriesData.evaluationItemName || '');
          setClickedTagName(seriesData.tagName || '');
        }
      } else {
        // 单线图模式或无法确定序列索引时，使用第一个trendData
        setClickedEvaluationItemName(trendData[0].evaluationItemName || '');
        setClickedTagName(trendData[0].tagName || '');
      }
    }

    setModalVisible(true);
    // 设置MarkerInfo为透明
    setIsMarkerTransparent(true);
  };

  // 处理span点击事件
  const handleSpanClick = (marker?: MarkerItem, markerChartData?: any) => {
    console.log('handleSpanClick marker', marker);
    console.log('handleSpanClick markerChartData', markerChartData);
    if (!marker) return;

    // 设置弹窗所需的状态信息
    setClickedPointData(undefined); // 不需要坐标点数据
    setClickedMarkerTitle(marker.title);
    setClickedMarkerType(marker.type);

    // 存储MarkerInfo传递的图表数据
    setMarkerTrendData(markerChartData);

    // 设置评估项名称和标签名称
    if (trendData.length > 0) {
      // 尝试根据marker的title查找匹配的trendData
      const matchedTrend = trendData.find(item =>
        item.evaluationItemName === marker.title || item.evaluationItemName === marker.name
      ) || trendData[0];

      setClickedEvaluationItemName(matchedTrend.evaluationItemName || '');
      setClickedTagName(matchedTrend.tagName || '');
    }

    // 打开弹窗
    setModalVisible(true);
    // 设置MarkerInfo为透明
    setIsMarkerTransparent(true);
  };

  // 关闭弹窗
  const handleCloseModal = () => {
    setModalVisible(false);
    // 恢复MarkerInfo的不透明度
    setIsMarkerTransparent(false);
  };

  // 获取弹窗标题
  const getModalTitle = () => {
    if (!clickedMarkerTitle) return '数据点详情';

    // 如果是多线图模式，显示带有系列名称的标题
    if (clickedPointData && trendData.length > 1) {
      const seriesData = trendData[clickedPointData.seriesIndex];
      if (seriesData && seriesData.tagName) {
        return `${clickedMarkerTitle} - ${seriesData.tagName}`;
      }
    }

    return clickedMarkerTitle;
  };

  const trendDataProps = useMemo(() => {
    return [
      trendData.find((item) => item.tagDesc === currentMarker?.title) ||
      trendData[0],
    ].filter(Boolean)
  }, [trendData, currentMarker]);

  console.log('selectedMarker', selectedMarker);
  return (
    <div className={styles["bg"]}>
      <div className={getBackgroundClassName()}>
        {getDynamicBackground() && (
          <video
            src={getDynamicBackground()}
            autoPlay
            muted
            loop
            playsInline
            onLoadedData={handleVideoLoaded}
            onError={(e) => {
              console.error("视频加载错误:", e);
              setVideoLoaded(false);
            }}
            style={{ opacity: videoLoaded ? 1 : 0, transition: 'opacity 0.5s ease' }}
          />
        )}
      </div>
      {!["param", "path"].includes(currentKey ?? "") && (
        <div className={styles["tab-container"]}>
          <Tab
            options={tabOptions}
            activeTab={activeTab}
            onChange={handleTabChange}
          />
        </div>
      )}
      {children}

      {/* 使用BarMarker组件单独渲染，不作为背景图的子元素 */}
      {["param", "path"].includes(currentKey ?? "") && (
        <BarMarker bars={getBars} viewportSize={viewportSize} />
      )}

      {/* anomaly模式：显示单个选中的标记点 */}
      {currentKey === "anomaly" &&
        selectedMarker &&
        selectedMarker.visible &&
        markerPixelPosition && (
          <MarkerInfo
            selectedMarker={selectedMarker}
            markerPixelPosition={markerPixelPosition}
            viewportSize={viewportSize}
            trendData={trendData} // 传递趋势图数据
            upperLimit={trendData?.[0]?.upperLimit}
            lowerLimit={trendData?.[0]?.lowerLimit}
            predictTime={trendData?.[0]?.predictTime} // 传递预测时间点
            isTransparent={isMarkerTransparent} // 传递透明度状态
            onSpanClick={(currentTrendData) => handleSpanClick(selectedMarker, currentTrendData)}
            onChartPointClick={(params) => handleChartPointClick(params, selectedMarker.title, selectedMarker.type, trendData)}
            onClose={() => setSelectedAnomaly(null)}
          />
        )}

      {/* question模式：显示当前轮播的标记点 */}
      {currentKey === "question" && currentMarker && (
        <MarkerInfo
          key={currentMarker.id}
          selectedMarker={currentMarker}
          markerPixelPosition={getMarkerPixelPosition(currentMarker.position)}
          viewportSize={viewportSize}
          trendData={trendDataProps}
          upperLimit={trendDataProps?.[0]?.upperLimit}
          lowerLimit={trendDataProps?.[0]?.lowerLimit}
          hideCloseIcon
          isQuestionMode={true}
          predictTime={currentMarker.predictTime} // 传递预测时间点
          isTransparent={isMarkerTransparent} // 传递透明度状态
          onSpanClick={(currentTrendData) => handleSpanClick(currentMarker, currentTrendData)}
          onClose={() => { }} // question模式不需要关闭
          onChartPointClick={(params) => handleChartPointClick(params, currentMarker.title, currentMarker.type, trendData.find((item) => item.evaluationItemName === currentMarker.title) || trendData[0])}
        />
      )}

      {currentKey === "param" && currentDevice !== "all" && confirmedMarker && (
        <MarkerInfo
          selectedMarker={confirmedMarker}
          markerPixelPosition={getConfirmedMarkerPixelPosition(parseInt(currentDevice as string, 10) - 1)}
          viewportSize={viewportSize}
          trendData={trendData}
          isQuestionMode={false}
          hideCloseIcon
          hideContentTitle
          predictTime={confirmedMarker.predictTime} // 传递预测时间点
          isTransparent={isMarkerTransparent} // 传递透明度状态
          onSpanClick={(currentTrendData) => handleSpanClick(confirmedMarker, currentTrendData)}
          onClose={() => { }}
          onChartPointClick={(params) => handleChartPointClick(params, confirmedMarker.title, confirmedMarker.type, trendData)}
        />
      )}

      {/* 图表点击弹窗 */}
      <ChartPointModal
        visible={modalVisible}
        title={getModalTitle()}
        type={clickedMarkerType}
        pointData={clickedPointData}
        evaluationItemName={clickedEvaluationItemName}
        tagName={clickedTagName}
        markerChartData={markerTrendData}
        predictTime={currentMarker?.predictTime || trendData?.[0]?.predictTime}
        onClose={handleCloseModal}
        upperLimit={markerTrendData?.upperLimit}
        lowerLimit={markerTrendData?.lowerLimit}
      />
    </div>
  );
};

export default BGContainer;
